﻿#include "Async.h"

#include <thread>

static CAsyncSystem* Instance=nullptr;
static std::thread::id MainThreadId;

void CAsyncSystem::Initialize(int64_t WorkThreadNum)
{
    assert(Instance==nullptr && "Only allow one CAsyncSystem exist at same time");
    Instance=new CAsyncSystem(WorkThreadNum);
    MainThreadId=std::this_thread::get_id();
}

void CAsyncSystem::Shutdown()
{
    Instance->ThreadPool->Shutdown();
    Instance->MainThread->Shutdown();

    delete Instance;
    Instance=nullptr;
}

CAsyncSystem *CAsyncSystem::Get()
{
    assert(Instance && "CAsyncSystem not initialized,invoke CAsyncSystem::Initialize before use it");
    return Instance;
}

CAsyncSystem::CAsyncSystem(int64_t WorkThreadNum)
{
    MainThread=new QueueSchedule();
    ThreadPool=new CThreadPoolSchedule(WorkThreadNum);
}

bool CAsyncSystem::IsInMainThread()
{
    return std::this_thread::get_id()==MainThreadId;
}

CAsyncSystem::~CAsyncSystem()
{
    MainThread->DoAllTasks();
    delete MainThread;

    
    delete ThreadPool;
}

void CAsyncSystem::DoMainThreadWork()
{
    if(MainThread->HasTasks())
    {
        MainThread->DoAllTasks();
    }

    //防止主线程占用过多CPU时间片，让出时间片
    std::this_thread::yield();
}
